package com.zhiyou100.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

/**
 * @author yang
 * @packageName ${NAME}
 * @className ${PACKAGE_NAME}
 * @Description TODO 拦截所有的请求，并且 设置编码集，将项目名称放入全局域中
 * @date 7/28/20
 * <p>
 * dispatcherTypes 设置 拦截所有
 * ERROR 拦截指定错误页面
 * FORWARD 拦截请求转发
 * INCLUDE 拦截请求包含
 * REQUEST 拦截直接请求 (默认)
 */
@WebFilter(filterName = "SetEncoding", urlPatterns = "/*", dispatcherTypes = {DispatcherType.ERROR, DispatcherType.FORWARD, DispatcherType.INCLUDE, DispatcherType.REQUEST, DispatcherType.ASYNC})
public class SetEncoding implements Filter {
    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {


        // 获取上下文对象
        ServletContext servletContext = req.getServletContext();

        // 获取项目名称
        String contextPath = servletContext.getContextPath();
        // 设置全局域的属性 projectName 为 项目名称
        servletContext.setAttribute("projectName", contextPath);


        // 获取 web.xml 的 初始化参数 characterEncoding 编码集
        String characterEncoding = servletContext.getInitParameter("characterEncoding");

        if (characterEncoding == null || characterEncoding.trim().length() == 0) {
            // 合理性判断
            characterEncoding = "UTF-8";
        }


        // 设置编码集
        req.setCharacterEncoding(characterEncoding);
        // 设定编码集
        resp.setContentType("text/html;charset=" + characterEncoding);
        // 设定类型


        // 放行
        chain.doFilter(req, resp);
    }

    @Override
    public void init(FilterConfig config) throws ServletException {
    }

}
